package com.ykdl.member.kid.set;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.kid.R;
import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.http.Network;
import com.ykdl.member.kid.beans.BabyProfileBean;
import com.ykdl.member.kid.beans.GetBabyProfileBean;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.member.kid.beans.StatuResult;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.models.FileMetas;
import com.ykdl.member.kid.prefs.BabyInfoPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.FileUtil;
import com.ykdl.member.kid.util.ResoureUtil;
import com.ykdl.member.views.MyWheelView;
import com.ykdl.member.views.WheelView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class MybabyActivity extends BaseScreen {
	
	private static final String TAG = "MybabyActivity";
	
	public static final int STATURE = 0;
	public static final int WEIGHT = 1;

	/** 宝宝的名字 */
	private EditText baby_name;
	private EditText baby_birth;
	// private Button boy, girl;
	private ImageView imageView;

	private static final int IMAGE_CAPTURE = 0;
	private static final int IMAGE_SECLET = 1;
	public static final int DATE_PICKER_ID = 2;
	public static final int PHOTORESOULT = 3;
	public static final String IMAGE_UNSPECIFIED = "image/*";
	public static final String OTHER_DATA = "other_data";
	// 宝宝属性
	// int sex;
	// boolean sex = true;
	private String name = "";
	private String birthDate = "";
	private String oldBirthDate = "";
	private String birth_date = "";
	private ColorStateList state1; // 性别选中颜色
	private ColorStateList state2; // 性别没选中颜色
	// 照片选择
	private AlertDialog dialog, back;
	private View layout, mStature_layout, mWeight_layout;
	private Button photograph, selectfile, picturecancel;
	private Uri imageUri; // 图片url
	private Calendar cal = Calendar.getInstance();
	private Bitmap newBitmap, bmap, resizeBmp, photo;// bitmap,
	boolean ISFOR;

	// other Data
	private TextView /* mConstellation, */mBloodtype;
	private TextView mStature, mWeight;
	private MyWheelView mStatureSelect, mWeightSelect;
	// private EditText mHistory, mFatherName, mMotherName;
	// private SharedPreferences mSaveOtherData;

	private String[] mMeterRanger = new String[] { "0", "1" };
	private String[] mCm10Ranger = new String[] { "00", "10", "20", "30", "40",
			"50", "60", "70", "80", "90" };
	private String[] mCm1Ranger = new String[] { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9" };
	private String mMeter = "m";
	private String mCM = "cm";

	private String[] mWeight1 = new String[] { "0", "10", "20", "30", "40",
			"50", "60" };
	private String[] mWeight2 = new String[] { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9" };
	private String[] mWeight3 = new String[] { "0.0", "0.1", "0.2", "0.3",
			"0.4", "0.5", "0.6", "0.7", "0.8", "0.9" };
	private String weight = "kg";

	String[] genderaray = new String[] {"小公主","小王子"};
	String[] blood_arr = null;
	private int gender_item_index = 0;
	private TextView gender;
	
	private int file_mate_id;
	
	
	private BitmapUtils mBmpUtils;
	private ProgressDialog mProgressDialog;

	private String from;// null 来自首页，有值，1 来自设置   ,2 来自爱问的用户设置,3来自设置的用户设置
	DatePickerDialog.OnDateSetListener dateSetLitener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			int mYear = year;
			int mMonth = monthOfYear;
			int mDay = dayOfMonth;
			int byear = cal.get(Calendar.YEAR) - year;
			if (year > cal.get(Calendar.YEAR)) {
				Toast.makeText(
						MybabyActivity.this,
						ResoureUtil.getResoure().getString(
								R.string.day_after_now), Toast.LENGTH_SHORT)
						.show();
				return;
			} else {
				if (byear > 6) {
					Toast.makeText(
							MybabyActivity.this,
							ResoureUtil.getResoure().getString(
									R.string.input_less_7), Toast.LENGTH_SHORT)
							.show();
					return;
				} else if (byear == 0) {
					if (monthOfYear > cal.get(Calendar.MONTH)) {
						Toast.makeText(
								MybabyActivity.this,
								ResoureUtil.getResoure().getString(
										R.string.day_after_now),
								Toast.LENGTH_SHORT).show();
						return;
					} else if (monthOfYear == cal.get(Calendar.MONTH)) {
						if (dayOfMonth > cal.get(Calendar.DAY_OF_MONTH)) {
							Toast.makeText(
									MybabyActivity.this,
									ResoureUtil.getResoure().getString(
											R.string.day_after_now),
									Toast.LENGTH_SHORT).show();
							return;
						} else {
							mDay = dayOfMonth;
						}
					}
					mYear = year;
					mMonth = monthOfYear;
					mDay = dayOfMonth;
				} else if (byear == 6) {
					if (monthOfYear < cal.get(Calendar.MONTH)) {
						// int s = cal.get(Calendar.MONTH);
						Toast.makeText(
								MybabyActivity.this,
								ResoureUtil.getResoure().getString(
										R.string.input_less_7),
								Toast.LENGTH_SHORT).show();
						return;
					} else if (monthOfYear == cal.get(Calendar.MONTH)) {
						if (dayOfMonth < cal.get(Calendar.DAY_OF_MONTH)) {
							Toast.makeText(
									MybabyActivity.this,
									ResoureUtil.getResoure().getString(
											R.string.input_less_7),
									Toast.LENGTH_SHORT).show();
							return;
						} else {
							mDay = dayOfMonth;
						}
					} else {
						mMonth = monthOfYear;
					}
				} else {
					mYear = year;
				}
			}
			mYear = year;
			String date = mYear + "-" + (mMonth + 1) + "-" + mDay;
			baby_birth.setText(date);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContent(R.layout.mybabyactivity_item);
		mBmpUtils = new BitmapUtils(this);
		setTopTitle("宝宝信息", 0, R.drawable.back_bg, new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		}, 0,
		R.drawable.save_bt_bg, new OnClickListener() {

			@Override
			public void onClick(View v) {
				save();
			}
		}, R.drawable.title_bg, false);
		blood_arr = getResources().getStringArray(R.array.ibaby_bloodtype_arr);
		from = getIntent().getStringExtra(KidAction.FROM);
		init();
		
		RegisterPhonebean bean = AccessTokenKeeper.readAccessToken(this);
		if (bean != null && !TextUtils.isEmpty(bean.getActor_id())) {
			mProgressDialog = ProgressDialog.show(this, null, getString(R.string.loading_data), true, true);
			Network.getInstance().getBabyProfile(bean.getActor_id(), new BabyProfileTag());
		} else {
			return;
		}
		
	}
	
	
	private void fillData(BabyProfileBean baby){
		if (baby == null) {
			return;
		}
		baby_name.setText(baby.getBaby_name());
		if (baby.getAvatar() != null && baby.getAvatar().getDownload_urls() != null && 
				baby.getAvatar().getDownload_urls().getMiddle() != null &&
				!TextUtils.isEmpty(baby.getAvatar().getDownload_urls().getMiddle().getUrl())) {
			mBmpUtils.display(imageView, baby.getAvatar().getDownload_urls().getMiddle().getUrl());
			file_mate_id = baby.getAvatar().getFile_id();
		}
		long time = (long) baby.getBirthday()*1000;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		baby_birth.setText(sdf.format(new Date(time)));
		gender.setText(genderaray[baby.getGender()]);
		
		mBloodtype.setText(baby.getBlood_type());
		
		mStature.setText(baby.getBorn_height()+"cm");
		mWeight.setText(baby.getBorn_weight()+"kg");
	}

	private void getBackDialog() {
		back = new AlertDialog.Builder(this)
				.setTitle(R.string.hmc_tx)
				.setMessage(R.string.ibaby_hint)
				.setPositiveButton(R.string.certain,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								MybabyActivity.this.finish();
							}
						})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						}).create();
	}

	private void init() {
		// mSaveOtherData = this.getSharedPreferences(OTHER_DATA,
		// Activity.MODE_PRIVATE);

		baby_name = (EditText) findViewById(R.id.ibaby_name);
		baby_birth = (EditText) findViewById(R.id.ibaby_birth);
		baby_birth.setOnClickListener(new showDatePicker());
		// boy = (Button) findViewById(R.id.ibaby_boy);
		// girl = (Button) findViewById(R.id.ibaby_girl);
		// select_img = (Button) findViewById(R.id.select_img);
		imageView = (ImageView) findViewById(R.id.ibaby_image);
		
		imageView.setOnClickListener(new SelectButtonListener());
		findViewById(R.id.ibb_headdiv).setOnClickListener(
				new SelectButtonListener());
		findViewById(R.id.ibb_birthdiv)
				.setOnClickListener(new showDatePicker());
		findViewById(R.id.ibb_namediv).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						baby_name.requestFocus();
					}
				});

		Resources res = getBaseContext().getResources();
		state1 = res.getColorStateList(R.color.btnColor);
		state2 = res.getColorStateList(R.color.btnColorSel);
		// boy.setOnClickListener(new BoyLitener());
		// girl.setOnClickListener(new GirlListener());

		getBackDialog();
		if (!BabyInfoPrefs.isInit()) {
			new BabyInfoPrefs(this);
		}

		OtherData otherData = new OtherData();
		// mConstellation = (TextView) findViewById(R.id.ibaby_constellation);
		mBloodtype = (TextView) findViewById(R.id.ibaby_bloodtype);
		mBloodtype.setOnClickListener(otherData);
		findViewById(R.id.ibb_bloodtype_div).setOnClickListener(otherData);

		// mFatherName = (EditText) findViewById(R.id.ibaby_father);
		// mMotherName = (EditText) findViewById(R.id.ibaby_mother);

		StatureSelect statureSelect = new StatureSelect();
		mStature = (TextView) findViewById(R.id.ibaby_stature);
		mStature.setOnClickListener(statureSelect);
		mStature_layout = findViewById(R.id.ibaby_stature_layout);
		mStature_layout.setOnClickListener(statureSelect);

		WeightSelect weightSelect = new WeightSelect();
		mWeight = (TextView) findViewById(R.id.ibaby_weight);
		mWeight.setOnClickListener(weightSelect);
		mWeight_layout = findViewById(R.id.ibaby_weight_layout);
		mWeight_layout.setOnClickListener(weightSelect);

		mStatureSelect = (MyWheelView) findViewById(R.id.ibaby_survey_wheel);
		mStatureSelect.setVisibility(View.INVISIBLE);
		mStatureSelect.findViewById(R.id.my_wheelview_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mStatureSelect.setMyGone();
			}
		});
		mStatureSelect.setOnWheelViewDataChanger(new UpdateStature());
		LinearLayout wheelGroup = (LinearLayout) mStatureSelect
				.findViewById(R.id.my_wheelview_group);
		mWheelViewSet(wheelGroup, mStatureSelect, STATURE);
		mStatureSelect.setTitle(ResoureUtil.getResoure().getString(
				R.string.input_bodyheight));

		mWeightSelect = (MyWheelView) findViewById(R.id.ibaby_weight_wheel);
		mWeightSelect.setVisibility(View.INVISIBLE);
		mWeightSelect.findViewById(R.id.my_wheelview_cancel).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mWeightSelect.setMyGone();
			}
		});
		mWeightSelect.setOnWheelViewDataChanger(new UpdateWeight());
		wheelGroup = (LinearLayout) mWeightSelect
				.findViewById(R.id.my_wheelview_group);
		mWheelViewSet(wheelGroup, mWeightSelect, WEIGHT);
		mWeightSelect.setTitle("输入体重");
		gender = (TextView) findViewById(R.id.ibb_gender);
		findViewById(R.id.ibb_genderdiv).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						AlertDialog alertDialog = new AlertDialog.Builder(
								MybabyActivity.this).setSingleChoiceItems(
								genderaray, gender_item_index,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										gender_item_index = which;
										gender.setText(genderaray[which]);
										dialog.cancel();
									}
								}).create();
						alertDialog.show();

					}

				});


		String babyInone = BabyInfoPrefs.getBabyInfo();
		init(babyInone);
	}

	private void mWheelViewSet(LinearLayout wheelGroup,
			MyWheelView mStatureSelect, int type) {
		switch (type) {
		case STATURE: {
			mStatureSelect.setWheelView(MyWheelView.OTHER, 3, null,
					MyWheelView.DATATYPE_STRING, mMeterRanger, mCm10Ranger,
					mCm1Ranger);

			for (int i = 0; i < wheelGroup.getChildCount(); i++) {
				WheelView wheelView = (WheelView) wheelGroup.getChildAt(i);
				switch (i) {
				case 0:
					wheelView.setLabel(mMeter);
					break;
				case 1:
					wheelView.setLabel(mCM);
					wheelView.setCyclic(true);
					break;
				case 2:
					wheelView.setLabel(mCM);
					wheelView.setCyclic(true);
					break;
				}
			}
			break;
		}
		case WEIGHT: {
			mStatureSelect.setWheelView(MyWheelView.OTHER, 3, null,
					MyWheelView.DATATYPE_STRING, mWeight1, mWeight2, mWeight3);

			for (int i = 0; i < wheelGroup.getChildCount(); i++) {
				WheelView wheelView = (WheelView) wheelGroup.getChildAt(i);
				switch (i) {
				case 0:
					wheelView.setLabel(weight);
					break;
				case 1:
					wheelView.setLabel(weight);
					wheelView.setCyclic(true);
					break;
				case 2:
					wheelView.setLabel(weight);
					wheelView.setCyclic(true);
					break;
				}
			}
			break;
		}
		}

	}

	/*
	 * 得到宝宝信息初始化数据
	 */
	private void init(String babyInone) {
		String name = "";
		String father = "";
		String mother = "";
		String height = "";
		String weight = "";
		String bolld = "";
		String allergic = "";
	}



	// 弹出选择框
	class StatureSelect implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
			.hideSoftInputFromWindow(MybabyActivity.this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
			mStatureSelect.setVisibility(View.VISIBLE);
			mStatureSelect.setInVisible(true);
			mStatureSelect.setMyVisible();
		}
	}

	class WeightSelect implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE))
			.hideSoftInputFromWindow(MybabyActivity.this.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
			mWeightSelect.setVisibility(View.VISIBLE);
			mWeightSelect.setInVisible(true);
			mWeightSelect.setMyVisible();
		}

	}
	
	private int getBloodIndex(String str){
		int index = 0;
		if (TextUtils.isEmpty(str)) {
			return index;
		} else {
			for (int i = 0; i < blood_arr.length; i++) {
				if (str.equals(blood_arr[i])) {
					index = i;
				}
			}
			return index;
		}
	}

	class OtherData implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.ibb_bloodtype_div:
			case R.id.ibaby_bloodtype:
				String blood_new = mBloodtype.getText().toString();
				int item_index = 0;
				if (blood_new != null && !"".equals(blood_new)) {
					for (int i = 0; i < blood_arr.length; i++) {
						if (blood_arr[i].equals(blood_new)) {
							item_index = i;
							break;
						}
					}
				}
				AlertDialog alertDialog = new AlertDialog.Builder(
						MybabyActivity.this).setSingleChoiceItems(blood_arr,
						item_index, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								mBloodtype.setText(blood_arr[which]);
								dialog.cancel();
							}
						}).create();
				alertDialog.show();
				break;
			}
		}
	}


	// 选择时间;
	private class showDatePicker implements OnClickListener {
		@Override
		public void onClick(View v) {
			showDialog(DATE_PICKER_ID);
			baby_birth.setInputType(InputType.TYPE_NULL);
		}
	}


	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == DATE_PICKER_ID) {
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH);
			int day = cal.get(Calendar.DAY_OF_MONTH);

			if (birth_date != null && !birth_date.equals("")) {
				String[] date = birth_date.split("-");
				if (date != null && date.length != 0) {
					year = Integer.parseInt(date[0]);
					month = Integer.parseInt(date[1]);
					day = Integer.parseInt(date[2]);
					month = month - 1;
				}
			}
			
			QLog.verbose(year + "-" + month + "-" + day);
			return new DatePickerDialog(this, dateSetLitener, year, month, day);
		}
		return null;
	}

	// 图片
	private class SelectButtonListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			shareDialog(MybabyActivity.this);
		}
	}

	/**
	 * FIXME Comment this method desc：shareDialog选择取图方式（拍照或相册）
	 * 
	 * @param context当前Activity环境下
	 */
	public void shareDialog(Context context) {
		LayoutInflater inflater = getLayoutInflater();
		layout = inflater.inflate(R.layout.pic_select_dialog,
				(ViewGroup) findViewById(R.id.selectpic_dialog));
		dialog = new AlertDialog.Builder(MybabyActivity.this).setView(layout)
				.show();

		photograph = (Button) layout.findViewById(R.id.pic_photograph);
		selectfile = (Button) layout.findViewById(R.id.pic_selectfile);
		picturecancel = (Button) layout.findViewById(R.id.pic_picturecancel);

		photograph.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					doPhotograph();
					dialog.cancel();
				} else {
					Toast.makeText(MybabyActivity.this,
							R.string.environment_state, 0).show();
				}
			}
		});
		selectfile.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doSelectFile();
				dialog.cancel();
			}
		});
		picturecancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
	}

	/**
	 * FIXME Comment this method desc：doPhotograph调用安卓系统的照相功能
	 */
	protected void doPhotograph() {
		new AsyncTask<Void, Void, String>() {
			protected String doInBackground(Void... params) {
				// ContentValues values = new ContentValues();
				// values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
				// imageUri = getContentResolver().insert(
				// MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
				String[] dir = FileUtil.getImagePath(mContext,
						KidConfig.IBABY_PATH);
				imageUri = Uri.parse("file://" + dir[0] + dir[1]);
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
				startActivityForResult(intent, IMAGE_CAPTURE);
				return null;
			}

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				onActivityResult(IMAGE_CAPTURE, 1, getIntent());
				super.onPreExecute();
				// Toast.makeText(BabyInfoEditor.this, "照相", 1).show();
			}

		}.execute();
	}

	/**
	 * FIXME Comment this method desc：doSelectFile从手机文件夹中取图片
	 */
	protected void doSelectFile() {
		new AsyncTask<Void, Void, String>() {
			protected String doInBackground(Void... params) {
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(intent, 1);
				return null;
			}

			@Override
			protected void onPreExecute() {
				// Toast.makeText(BabyInfoEditor.this, "查找文件夹", 1).show();
				onActivityResult(IMAGE_SECLET, 1, getIntent());
				super.onPreExecute();
			}
		}.execute();
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case IMAGE_SECLET:
			if (data != null) {
				imageUri = data.getData();
				if (resultCode == RESULT_OK) {
					startPhotoZoom(imageUri);
				}
			}
			break;
		case IMAGE_CAPTURE:
			if (resultCode == RESULT_OK) {
				startPhotoZoom(imageUri);
			}
			break;
		case PHOTORESOULT:
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
					try {
						saveFile(lessBitmap(photo, 480, 600), "headpic.jpg");
						ISFOR = true;
					} catch (IOException e) {
						QLog.debug(TAG, "set baby img false " + e.toString());
					}
				}
			}
			break;
		}

	}

	/**
	 * FIXME Comment this method desc：lessBitmap缩放图片
	 * 
	 * @param map原图片
	 * @param destWith缩放后的宽度
	 * @param destHeight缩放后的高度
	 * @return Bitmap处理后的图片
	 */

	private Bitmap lessBitmap(Bitmap map, int destWith, int destHeight) {
		if (map == null) {
			return null;
		}
		int w = map.getWidth();
		int h = map.getHeight();
		Matrix matrix = new Matrix();
		if (w > h) {
			matrix.postRotate(90, (float) w / 2, (float) h / 2);
		}
		/*
		 * float scaleW = (float) destWith / w; float scaleH = (float)
		 * destHeight / h; matrix.postScale(scaleW, scaleH);
		 */
		newBitmap = Bitmap.createBitmap(map, 0, 0, w, h, matrix, true);
		return newBitmap;
	}

	/**
	 * FIXME Comment this method desc：saveFile创建图片文件
	 * 
	 * @param bm
	 *            图片
	 * @param fileName
	 *            图片名字
	 * @throws IOException
	 *             抛出IO异常
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		File dirFile = new File(KidConfig.URI_HEAD);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File file = new File(KidConfig.URI_HEAD + "/" + fileName);
		file.createNewFile();
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(file));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		imageView.setImageBitmap(bm);
		bos.flush();
		bos.close();
		// startPhotoZoom(Uri.fromFile(file));
		putphoto(file);
	}

	/**
	 * FIXME Comment this method desc：startPhotoZoom图片剪切的方法
	 * 
	 * @param uri
	 *            图片的URI地址
	 */

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}

	// 保存
	private void save() {
		String height = mStature.getText().toString().replace("cm", "");
		if (TextUtils.isEmpty(height)) {
			Toast.makeText(this, "请输入宝宝身高", 1).show();
			return;
		}
		String weight = mWeight.getText().toString().replace("kg", "");
		if (TextUtils.isEmpty(weight)) {
			Toast.makeText(this, "请输入宝宝体重", 1).show();
			return;
		}
		String strBlood = mBloodtype.getText().toString();
		if (TextUtils.isEmpty(strBlood)) {
			Toast.makeText(this, "请选择宝宝血型", 1).show();
			return;
		}
		name = baby_name.getText().toString();
		if (TextUtils.isEmpty(name)) {
			Toast.makeText(this, "请输入宝宝昵称", 1).show();
			return;
		}
		birthDate = baby_birth.getText().toString();
		birthDate = birthDate.substring(birthDate.indexOf("：") + 1);
		if (TextUtils.isEmpty(birthDate)) {
			Toast.makeText(this, "请输入宝宝年龄", 1).show();
			return;
		}
		String[] birthString = birthDate.split("-");
		for (int i = 1; i < birthString.length; i++) {
			if (birthString[i].length() == 1) {
				birthString[i] = "0" + birthString[i];
			}
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, Integer.valueOf(birthString[0]));
		calendar.set(Calendar.MONTH, Integer.valueOf(birthString[1])-1);
		calendar.set(Calendar.DAY_OF_MONTH, Integer.valueOf(birthString[2]));
		birthDate = birthString[0] + "-" + birthString[1] + "-"
				+ birthString[2];
		if (!birthDate.equals(oldBirthDate)) {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		}
		float birthday = (float) (calendar.getTimeInMillis()/1000);
		showProgress(getString(R.string.progres_dialog_loading));
		
		Network.getInstance().perfectBabyProfile(name, birthday, getBloodIndex(strBlood), Integer.parseInt(height), 
				Float.valueOf(weight), gender_item_index, file_mate_id, new PerfectTag());
		
	}


	/**
	 * FIXME Comment this method desc：fitSizeImg
	 * 
	 * @param path文件路径
	 * @return Bitmap返回加工后的图片
	 */
	public Bitmap fitSizeImg(String path) {
		if (path == null || path.length() < 1)
			return null;
		File file = new File(path);
		resizeBmp = null;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		// if (file.length() < 20480) { // 0-20k
		opts.inSampleSize = 1;
		// } else if (file.length() < 51200) { // 20-50k
		// opts.inSampleSize = 2;
		// } else if (file.length() < 307200) { // 50-300k
		// opts.inSampleSize = 4;
		// } else if (file.length() < 819200) { // 300-800k
		// opts.inSampleSize = 6;
		// } else if (file.length() < 1048576) { // 800-1024k
		// opts.inSampleSize = 8;
		// } else {
		// opts.inSampleSize = 10;
		// }
		resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts);
		return resizeBmp;
	}

	@Override
	protected void onResume() {
		ImageLoader.getInstance().setCurrentActivity(TAG);
		super.onResume();
		// 统计数据
//		if (ISFOR == true) {
//			bmap = fitSizeImg(KidConfig.HEAD);
//			if (bmap != null) {
//				imageView.setImageDrawable(Drawable
//						.createFromPath(KidConfig.HEAD));
//				// imageView.setImageBitmap(bmap);
//			} else {
//				imageView.setImageDrawable(imageView.getResources()
//						.getDrawable(R.drawable.defult_user_icon));
//			}
//		} else {
//			bmap = fitSizeImg(KidConfig.HEAD2);
//			if (bmap != null) {
//				imageView.setImageDrawable(Drawable
//						.createFromPath(KidConfig.HEAD2));
//				// imageView.setImageBitmap(bmap);
//			} else {
//				imageView.setImageDrawable(imageView.getResources()
//						.getDrawable(R.drawable.defult_user_icon));
//			}
//		}

	}

	class UpdateStature implements MyWheelView.OnWheelViewDataChanger {
		@Override
		public void updataByChanger(String data) {
			String[] datas = data.split(",");
			if (datas.length == 3) {
				int meter = Integer.valueOf(datas[0]);
				int cm10 = Integer.valueOf(datas[1]);
				int cm1 = Integer.valueOf(datas[2]);
				String result = "";
				if (meter == 0) {
					result = (cm10 + cm1) + mCM;
				} else {
					result = (100 + (cm10 + cm1)) + mCM;
				}
				mStature.setText(result);
			}
		}
	}

	class UpdateWeight implements MyWheelView.OnWheelViewDataChanger {
		@Override
		public void updataByChanger(String data) {
			String[] datas = data.split(",");
			if (datas.length == 3) {
				float weight1 = Float.valueOf(datas[0]);
				float weight2 = Float.valueOf(datas[1]);
				float weight3 = Float.valueOf(datas[2]);
				String result = (weight1 + weight2 + weight3) + weight;
				mWeight.setText(result);
			}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (mStatureSelect.getMyVisibility() == View.VISIBLE) {
				mStatureSelect.setMyGone();
				return true;
			} else if (mWeightSelect.getMyVisibility() == View.VISIBLE) {
				mWeightSelect.setMyGone();
				return true;
			} else {
				finish();
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	//=========================================================================
	
	
	private class PerfectTag implements ITag<StatuResult> {

		@Override
		public void refreshUI(StatuResult t, DataState ds) {
			finishProgress();
			if (t != null && t.getResult() == 0) {
				Toast.makeText(MybabyActivity.this, "修改资料成功", Toast.LENGTH_LONG).show();
				finish();
			} else {
				Toast.makeText(MybabyActivity.this, "修改资料失败", Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			finishProgress();
			if (TextUtils.isEmpty(parseError.getErrMsg())) {
				Toast.makeText(MybabyActivity.this, "修改资料失败", Toast.LENGTH_LONG).show();
				return false;
			} else {
				Toast.makeText(MybabyActivity.this, parseError.getErrMsg(), Toast.LENGTH_LONG).show();
				return true;
			}
		}

		@Override
		public void refreshCancel() {
			
		}
		
	}
	
	public void putphoto(File file) {
		String  pageurl = KidConfig.UPLOAD_PHOTO;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadFile(pageurl,file);
		TaskManager.startHttpRequest(request, new PutphotoTag(),  FileMetas.class);
	}
	
	class PutphotoTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof FileMetas) {
				FileMetas bean = (FileMetas)t;
				file_mate_id = bean.getFile_id();
				if (file_mate_id != 0) {
					Toast.makeText(MybabyActivity.this, "图片上传成功", Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(MybabyActivity.this, "图片上传失败", Toast.LENGTH_LONG).show();
				}
			} else {
				Toast.makeText(MybabyActivity.this, "图片上传失败", Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			Toast.makeText(MybabyActivity.this, "图片上传失败", Toast.LENGTH_LONG).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			
		}
		
	}
	
	private class BabyProfileTag implements ITag<GetBabyProfileBean> {

		@Override
		public void refreshUI(GetBabyProfileBean t, DataState ds) {
			if (mProgressDialog != null) mProgressDialog.dismiss();
			if (t != null && t.getBaby_profile() != null) {
				fillData(t.getBaby_profile());
				Toast.makeText(MybabyActivity.this, "宝贝详细资料获取成功", 1).show();
			} else {
				Toast.makeText(MybabyActivity.this, "宝贝详细资料获取失败", 1).show();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			if (mProgressDialog != null) mProgressDialog.dismiss();
			Toast.makeText(MybabyActivity.this, "宝贝详细资料获取失败", 1).show();
			return true;
		}

		@Override
		public void refreshCancel() {}
		
	}
}
